import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

public class DetailDaoImpl implements DetailDao{

	public int add(Detail detail) {
		String sql = "insert into atm_detail(user_id, amount, desc_msg, card_num, create_time) values("+detail.userId +", "+detail.amount+", '"+detail.descMsg+"', "+ detail.cardNum +",now());";
		System.out.println(sql);

		Connection conn = null;
		Statement sm = null;
		int rows = 0;

		try {
			conn = DateBaseUtil.getConn();
			sm = conn.createStatement();
			rows = sm.executeUpdate(sql);
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != sm) {
					sm.close();
				}
			} catch(SQLException se) {
				se.printStackTrace();
			}
			
		}

		return rows;
	}

	public List<Detail> query(String cardNum) {
		
		String sql = "select id, user_id, amount, card_num, desc_msg, create_time from atm_detail where card_num = '"+cardNum+"';";
		System.out.println(sql);

		Connection conn = null;
		Statement sm = null;
		ResultSet rs = null;

		List<Detail> details = new ArrayList<Detail>();
		Detail detail = null;

		try {
			conn = DateBaseUtil.getConn();
			sm = conn.createStatement();
			rs = sm.executeQuery(sql);

			while (rs.next()) {
				int id = rs.getInt("id");
				int userId = rs.getInt("user_id");
				int amount = rs.getInt("amount");
				String descMsg = rs.getString("desc_msg");
				Timestamp tt = rs.getTimestamp("create_time");

				detail = new Detail();
				detail.id = id;
				detail.userId = userId;
				detail.cardNum = cardNum;
				detail.amount = amount;
				detail.descMsg = descMsg;
				detail.createTime = new Date(tt.getTime());
				
				details.add(detail);

			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != rs) {
					rs.close();
				}
				if (null != sm) {
					sm.close();
				}
			} catch(SQLException se) {
				se.printStackTrace();
			}
			
		}

		return details;

	}
}